#include <my_header.h>

typedef int DataType;
typedef struct node
{
    DataType data;
    struct node* next;
}Node;

typedef struct
{
    Node *tail;
    Node *head;
    int size;
}Linklist;

typedef struct share_value_s{
    int flag;
    pthread_mutex_t mLock;
    Linklist * list;
}share_value_t;

void * threadFunc(void * arg);
int tailInsert(Linklist *plist,int data);
void del_node(Linklist *plist);
/* usage */
int main(int argc, char *argv[])
{
    ARGS_CHECK(argc,1);

    share_value_t share_value;
    share_value.flag = 0;
    share_value.list = (Linklist *)calloc(1,sizeof(Linklist));
    pthread_mutex_init(&share_value.mLock,NULL);

    pthread_t tid;
    int ret_create = pthread_create(&tid,NULL,threadFunc,&share_value);
    THREAD_ERROR_CHECK(ret_create,"pthread_create");

    while(1)
    {
        pthread_mutex_lock(&share_value.mLock);
        if(share_value.flag == 1)
        {
            del_node(share_value.list);
            pthread_mutex_unlock(&share_value.mLock);
            break;
        }
        pthread_mutex_unlock(&share_value.mLock);
    }

    printf("del node is finished\n");
    pthread_join(tid,NULL);

    return 0;
}

void * threadFunc(void * argc)
{
    share_value_t * pshare_value = (share_value_t * )argc;
    for(int i = 0 ; i < 10; i++)
    {
        tailInsert(pshare_value->list,i);
    }
    pthread_mutex_lock(&pshare_value->mLock);
    pshare_value->flag = 1;
    pthread_mutex_unlock(&pshare_value->mLock);

    pthread_exit(NULL);

}
int tailInsert(Linklist *plist,int data)
{
    Node *new_node = (Node *)calloc(1,sizeof(Node));
    new_node->data =data;
    if(plist->size == 0)
    {
        plist->head = new_node;
        plist->tail = new_node;
    }
    else
    {
        plist->tail->next = new_node;
        plist->tail =new_node;
    }
    plist->size ++;
    return 1;
}

void del_node(Linklist *plist)
{
    if(plist == NULL) return;
    Node * cur = plist->head;
    while(cur != NULL)
    {
        Node *tmp = cur->next;
        printf("%d ",cur->data);
        free(cur);
        cur = tmp;
    }
    plist->head = NULL;
    plist->tail = NULL;
    plist->size = 0;
    printf("\n");
}
